package com.emit.exception;

import com.emit.view.ResultView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * global exception handle
 *
 * @author zhangchao
 * @version 1.0.0
 * @date 2020-08-18
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    @Autowired
    private MessageSource messageSource;

    /**
     * handle customer exception
     * @param e customer exception
     * @return return the result to frontend
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResultView<String> bizExceptionHandler(BizException e){
        String message = messageSource.getMessage("error.service",null, LocaleContextHolder.getLocale());
        logger.error(message,e.getMsg());
        ResultView<String> resultView = new ResultView<>();
        resultView.setStatus(-1);
        resultView.setCode(e.getCode());
        resultView.setMsg(e.getMsg());
        return resultView;
    }

    /**
     * handle null point exception
     * @param e null point exception
     * @return return the result to frontend
     */
    @ExceptionHandler(value =NullPointerException.class)
    @ResponseBody
    public ResultView<String> exceptionHandler(NullPointerException e){
        String message = messageSource.getMessage("error.A1001",null, LocaleContextHolder.getLocale());
        logger.error(message,e);
        ResultView<String> resultView = new ResultView<>();
        resultView.setStatus(-1);
        resultView.setCode("A1001");
        resultView.setMsg(e.toString());
        return resultView;
    }

    /**
     * handle unknown exception
     * @param e unknown exception
     * @return return the result to frontend
     */
    @ExceptionHandler(value =Exception.class)
    @ResponseBody
    public ResultView<String>  exceptionHandler(Exception e){
        String message = messageSource.getMessage("error.A1000",null, LocaleContextHolder.getLocale());
        logger.error(message,e);
        ResultView<String> resultView = new ResultView<>();
        resultView.setStatus(-1);
        resultView.setCode("A1000");
        resultView.setMsg(e.toString());
        return resultView;
    }
}
